package com.phpxiu.app.upload;

import android.os.AsyncTask;

import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.utils.KKYUtil;
import com.tencent.cos.COSClient;
import com.tencent.cos.COSClientConfig;
import com.tencent.cos.common.COSEndPoint;
import com.tencent.cos.model.PutObjectRequest;


/**
 * @file
 * @brief 图片上传任务
 * @author 吴金洲
 * @note  基于腾讯云对象存储4.0+服务实现
 * callBack 上传完成回调
 */
public class UploadPhotoTask extends AsyncTask<String,Void,Void> {
    private UploadUIHandler callBack;
    private final static String TID="10043856";
    private final static String BUCKET="kkylive2";
    private final static COSClientConfig CFG = new COSClientConfig();
    static {
        CFG.setConnectionTimeout(5000);//上传请求5秒超时
        CFG.setMaxConnectionsCount(1);//最大并发数
        CFG.setEndPoint(COSEndPoint.COS_SH);
        CFG.setMaxRetryCount(0);//上传失败，不重试
    }

    private static String sign;//签名

    /**
     * 上传服务管理
     */
    private static COSClient cosClient;

    private PutObjectRequest request;
    private String path;
    private String dir;
    public UploadPhotoTask(UploadUIHandler callBack) {
        request=new PutObjectRequest();
        this.callBack = callBack;
    }

    /**
     * 更新签名
     * @param s 签名字符串
     */
    public static void refreshSign(String s){
        sign=s;
    }

    public void executeUpload(String path,String dir){
        this.path=path;
        this.dir=dir;
        execute();
    }

    /**
     * 执行任务过程
     * @param params
     * @return
     */
    @Override
    protected Void doInBackground(String... params) {
        request.setBucket(BUCKET);
        String photo="/"+dir+"/"+ MySelfInfo.getInstance().getId() + "_" + System.currentTimeMillis() + ".jpg";
        request.setCosPath(photo);
        request.setSrcPath(path);
        request.setSign(sign);
        request.setListener(callBack);
        cosClient.putObject(request);
        return null;
    }

    @Override
    protected void onCancelled() {
        if(request!=null){
            request.setListener(null);
        }
        super.onCancelled();
    }

    /**
     * 就绪
     */
    @Override
    protected void onPreExecute() {
        if(cosClient==null){
            cosClient=new COSClient(KKYApp.getInstance(),TID,CFG,null);
        }
        sign=MySelfInfo.getInstance().getCosSig();
        if(sign==null||"".equals(sign)){
            KKYUtil.log("签名为空，不能上传");
            try {
                cancel(true);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
